package com.hmdp.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexPatterns;
import com.hmdp.utils.RegexUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    private final StringRedisTemplate redisTemplate;

    /**
     *     实现登陆功能
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        String phone = loginForm.getPhone();
        // 1. 校验手机号是否符合规范
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.不符合规范直接return结束
            return Result.fail("手机号格式错误！");
        }

        // 2.从redis中获取验证码
//        Object code = session.getAttribute("code");
        Object code = redisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        String cacheCode = loginForm.getCode();
        if(code == null || !code.equals(cacheCode)){
            return Result.fail("验证码错误！");
        }

        // 3. 根据手机号查询用户
        User user = query().eq("phone", phone).one();

        // 4. 用户不存在需要插入表中
        if(user == null){
            user= createUserWithPhone(phone);
        }

        // 5.无论用户存在与否，保存到redis中
        // 5.1 生成一个token作为令牌和key
        String token = UUID.randomUUID().toString();

        //5.2 user对象转userDTO再转哈希
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        Map<String,Object> userMap= BeanUtil.beanToMap(userDTO,new HashMap<>(),CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName,filedValue)-> filedValue.toString()));

        // 5.3 保存数据到redis
        redisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,userMap);

        // 5.4 设置有效期
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL,TimeUnit.MINUTES);

        // 6. 返回token给前端
        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(6));
        save(user);
        return user;
    }

    /**
     * 发送短信验证码
     * @param phone
     * @param session
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {

        // 1.校验手机号是否符合规范
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.不符合规范直接return结束
            return Result.fail("手机号格式错误！");
        }

        // 3.生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 4.将短信验证码保存到session中
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone,code,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 5.发送短信验证码
        log.debug("验证码发送成功{}",code);

        return Result.ok();
    }
}
